package com.stationpc.dock

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.KeyEvent
import android.view.accessibility.AccessibilityEvent
import android.content.Intent
import com.stationpc.dock.service.DockOverlayService

class DockAccessibilityService : AccessibilityService() {

    private var isPageDownPressed = false
    private val handler = Handler(Looper.getMainLooper())
    private var lastPressTime: Long = 0
    private val DEBOUNCE_INTERVAL = 300L // 300ms

    override fun onServiceConnected() {
        super.onServiceConnected()
        val info = AccessibilityServiceInfo().apply {
            eventTypes = AccessibilityEvent.TYPE_WINDOWS_CHANGED or AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
            feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
            flags = AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS
        }
        serviceInfo = info
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        // No implementation needed for this use case
    }

    override fun onKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastPressTime < DEBOUNCE_INTERVAL) {
                return true
            }
            lastPressTime = currentTime

            when (event.action) {
                KeyEvent.ACTION_DOWN -> {
                    if (!isPageDownPressed) {
                        isPageDownPressed = true
                        handler.postDelayed({
                            if (isPageDownPressed) {
                                // Long press detected
                                Log.d("DockAccessibilityService", "Long press PAGE_DOWN detected")
                                toggleAppDock()
                            }
                        }, LONG_PRESS_DELAY)
                    }
                }
                KeyEvent.ACTION_UP -> {
                    // Ignore short press and do not toggle dock
                    isPageDownPressed = false
                    handler.removeCallbacksAndMessages(null)
                }
            }
            return true
        }
        return super.onKeyEvent(event)
    }

    private fun toggleAppDock() {
        val intent = Intent(this, DockOverlayService::class.java).apply {
            action = DockOverlayService.ACTION_TOGGLE_VISIBILITY
        }
        startService(intent)
    }

    override fun onInterrupt() {
        // Handle service interruption if necessary
    }

    companion object {
        private const val LONG_PRESS_DELAY = 1000L // 1 second for long press
    }
}
